﻿/*
 * Copyright © 2020, Wuxi Safover Intelligent Technology Co., Ltd. All rights reserved.
 * 
 * 无锡安永智能科技有限公司版权所有，未经许可，不得用于商业用途
 * 
 * Visit: https://www.safover.com/ 
 */

using System;
using System.IO.Ports;
using System.Timers;
using Safover.LidarCollector.Core;
using Safover.LidarCollector.Extensions;
using Safover.LidarCollector.Models;

namespace GPS.BeiTian
{
    public class VirtualNema0183GpsLocationDevice : GpsLocatorDevice
    {
        #region Singleton
        public static GpsLocatorDevice Instance { get; } = new VirtualNema0183GpsLocationDevice();

        private VirtualNema0183GpsLocationDevice()
        {
            UtcTimestamp = TimeUtils.BeiJingTimeToUtcTimestamp(DateTime.Now);
            RealLatitude = 88.123456;
            RealLongitude = 66.123456;
        }

        #endregion

        private Timer Timer { get; set; }

        bool IsOpen { get; set; }

        public override string DeviceType => "VirtualNema0183GpsLocationDevice";

        public override bool IsSerialPortOpen => IsOpen;

        public override GpsInformation ObtainGpsInformation()
        {
            return new GpsInformation
            {
                Time = DateTime.UtcNow,
                Longitude = DefaultLongitude,
                Latitude = DefaultLatitude,
                Altitude = DefaultAltitude,
            };
        }

        protected override bool DoCloseSerialPort()
        {
            IsOpen = false;

            if (Timer != null) 
            {
                Timer.Elapsed -= OnTimedEvent;
                Timer.Enabled = false;
            }

            return true;
        }

        protected override void DoOpenSerialPort()
        {
            if (IsSerialPortOpen)
            {
                throw new InvalidOperationException($"Port is already open, device=[{DeviceType}].");
            }

            Timer = new Timer(2000);
            // Hook up the Elapsed event for the timer. 
            Timer.Elapsed += OnTimedEvent;
            Timer.AutoReset = true;
            Timer.Enabled = true;

            IsOpen = true;
        }

        private void OnTimedEvent(object sender, ElapsedEventArgs e)
        {
            OnDataReceived(null, null);
        }

        protected override void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            DeviceReadingsUpdated?.Invoke(this, new GpsLocatorReadingsUpdatedEventArgs
            {
                Longitude = DefaultLongitude,
                Latitude = DefaultLatitude,
            });

        }
    }
}
